package com.cyberEye.servlet;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.team2.shared.ServerProduct;
import com.team2.shared.SharedConstants;
import com.team2.shoppingService.Configuration;
import com.team2.shoppingService.Shopper;
import com.team2.shoppingService.Util;

@SuppressWarnings("serial")
public class ProductServlet extends HttpServlet {

	public HashMap<String, String> parseQueryString(String querystring) {
		HashMap<String, String> parameters = new HashMap<String, String>();
		for (String pairString : querystring.split("&")) {
			String[] pair = pairString.split("=");
			if (pair.length == 2) {
				parameters.put(pair[0], pair[1]);
			}
		}
		return parameters;
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		

		// Getting Parameters
		HashMap<String, String> parameters = parseQueryString(req
				.getQueryString());
		String tags = parameters.get("tags");
		String category = parameters.get("category");
		String imageMatch = parameters.get(SharedConstants.isImageMatch);
		String token = parameters.get("token");
		String Online= parameters.get("isOnline");
		System.out.println("Get Product Request<doPost,tags:"+tags+">");
		if(token ==null || !token.equals(Util.computeHashFromBytes(SharedConstants.TOKEN.getBytes()))){
			resp.setStatus(999);
			resp.getWriter().println("Unauthorized Access! Token is missing");
			return;
		}
		
		boolean isImageMatch = false;
		boolean isOnline = false;
		if (imageMatch != null || !imageMatch.isEmpty()) {
			isImageMatch = imageMatch.equals(SharedConstants.TRUE);
		}
		if (Online == null || Online.isEmpty()) {
			isOnline = false;
			
		}else{
			isOnline = Online.equals(SharedConstants.TRUE);
		}
		System.out.println(tags + "," + category);

		// set up path prefix
		String prefix = getServletContext().getRealPath(
				"/WEB-INF/WebParserConfigFiles")
				+ "/";
		System.out.println(prefix);
		Configuration.setPathPrefix(prefix);
		Configuration.setContext(getServletContext().getRealPath("/"));

		resp.setContentType("text/plain");

		if (tags == null || tags.isEmpty()) {
			resp.setStatus(666);
			resp.getWriter().println("Parameter [tags] is required!");
			return;
		}
		// Start Processing
		// encapulate response with byte array output stream
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		ObjectOutputStream oout = new ObjectOutputStream(bout);
		// Start querying the products
		ArrayList<ServerProduct> products = null;
		if (category == null || category.isEmpty()) {
			products = Shopper.searchProducts(tags);
		}if(isOnline){
			products = Shopper.searchOnlineProducts(tags);
		} 
		else {
			products = Shopper.searchProducts(tags, category);
		}

		if (isImageMatch) {
			FileOutputStream fos = null;
			String requestImagePath = getServletContext().getRealPath(
					Configuration.TEMPPATH);
			File tempDir=new File(requestImagePath);
			if(!tempDir.exists()){
				tempDir.mkdirs();
				System.out.println("TEMP foler created");
			}
			requestImagePath += "/"+Configuration.getNextRequestNumber()+".jpg";
			System.out.println(requestImagePath);
			try {
				fos = new FileOutputStream(requestImagePath);
				InputStream content = req.getInputStream();
				;
				byte[] buffer = new byte[8000];
				int numberRead = content.read(buffer);
				while (numberRead > 0) {
					fos.write(buffer, 0, numberRead);
					numberRead = content.read(buffer);
				}
				fos.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				resp.getWriter().println("image upload failed");
				return;
			}
			products = Shopper.computeSimilarity(
					requestImagePath, products);
		}
		// output the products
		oout.writeObject(products);
		oout.close();
		resp.getOutputStream().write(bout.toByteArray());
		resp.setStatus(200);
	}

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		String token = req.getParameter("token");
		
		if(token ==null || !token.equals(Util.computeHashFromBytes(SharedConstants.TOKEN.getBytes()))){
			resp.setStatus(999);
			resp.getWriter().println("Unauthorized Access! Token is missing");
			System.out.println("Unauthorized Access! Token is missing");
			return;
		}
		
		
		// set up path prefix
		String prefix = getServletContext().getRealPath(
				"/WEB-INF/WebParserConfigFiles")
				+ "/";
		//System.out.println(prefix);
		Configuration.setPathPrefix(prefix);

		resp.setContentType("text/plain");
		String tags = req.getParameter("tags");

		if (tags == null || tags.isEmpty()) {
			resp.setStatus(666);
			resp.getWriter().println("Parameter [tags] is required!");
			return;
		}
		String category = req.getParameter("category");
		System.out.println("Get Product Request!!<doGet, tags:"+tags+", category:"+category+">");

		// encapulate response with byte array output stream
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		ObjectOutputStream oout = new ObjectOutputStream(bout);
		ArrayList<ServerProduct> products = null;
		// Start querying the products
		if (category == null || category.isEmpty()) {

			products = Shopper.searchProducts(tags);
			return;
		}else{
		products = Shopper.searchProducts(tags, category);
		}
		oout.writeObject(products);
		oout.close();
		resp.getOutputStream().write(bout.toByteArray());
		resp.setStatus(200);
	}

}
